<?php

abstract class Application_Model_Abstract {

    protected $_dbTable;

    public function insert(array $data){
        return $this->_dbTable->insert($data);
    }
    
    public function find($id) {
        return $this->_dbTable->find($id)->current();
    }
    
    public function update(array $data, $where){
        return $this->_dbTable->update($data, $this->_dbTable->getAdapter()
               ->quoteInto("Id = ?", $where));
    }
    
    public function delete($where){
        return $this->_dbTable->delete($this->_dbTable->getAdapter()
                ->quoteInto("Id = ?", $where));
    }
    
    public function search(array $params) {
        $str = isset($params['str']) ? $params['str'] : "";
        $filtro = isset($params['filtro']) ? $params['filtro'] : "";
        $page = isset($params['page']) ? (int) $params['page'] : 1;
        $perage = isset($params['limit']) ? (int) $params['limit'] : 10;

        if (!empty($str)) {
            $where = $filtro . " like '%" . $str . "%'";
            $registros = $this->_dbTable->fetchAll($where);
            $paginator = Zend_Paginator::factory($registros);
        }
        else{
            $registros = $this->_dbTable->fetchAll();
            $paginator = Zend_Paginator::factory($registros);
        }

        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage($perage);

        $result = array();
        
        foreach ($paginator as $v) {
            $result[] = $v->toArray();
        }
        
        $result['total'] = count($registros);
        
        return $result;
    }
}

